﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StateGrid;
using StateGrid.WWQK;
using StateGrid.User;
using StateGrid.GlobalVariables;
using iTextSharp.text.pdf;
using StateGrid.OperationLog;

public partial class AddPM : System.Web.UI.Page
{
    /// <summary>
    /// 外文期刊操作对象
    /// </summary>
    private WWQK_DAO wwqkDAO = new WWQK_DAO();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!UserManageDAO.IsLogin((User)Session["login"]))
        {
            GlobalMethod.RedirectLogin(Response); 
            return;
        }

        if (!this.IsPostBack)
        {
            this.BindData();
        }

    }

    /// <summary>
    /// 绑定初始化数据
    /// </summary>
    private void BindData()
    {
        String currentSYBM = (String)Request["sybm"];

        if (null == currentSYBM || "".Equals(currentSYBM))
        {
            String message = "错误：没有找到当前索引编码对应的期刊索引";
            Response.Redirect(GlobalResource.ERROR_PAGE+"?message="+message);
            return;
        }

        //添加返回按钮
        String sybm = (currentSYBM.Split('-'))[0];
        this.backHyperLink.NavigateUrl = GlobalWWQK.LISTPM_PAGE + "?sybm=" + sybm;

        //获取中文期刊索引目录
        WWQK_SYML wwqkSYML = this.wwqkDAO.getWwqkSYMLBySybm(currentSYBM);

        if (null == wwqkSYML)
        {
            String message = "错误：没有找到当前索引编码对应的期刊索引";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }
        //年份
        String nf = (String)Request["nf"];
        this.nfTextBox.Text = nf;

        //期号
        String qh = (String)Request["qh"];

        this.qhTextBox.Text = qh;
        if (!ValidateNF()||!ValidateQH())
        {
            String message = "错误：您选择的年份或期号有误";
            Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
            return;
        }
        
        //中文名称
        this.zwmcTextBox.Text = wwqkSYML.zwmc;
        //外文名称
        this.wwmcTextBox.Text = wwqkSYML.wwmc;

        //ZWQK_PM zwqkPM = this.zwqkDAO.getMaxZwqkPM(currentSYBM, "2000", "01");
        //索引编码
        this.sybmTextBox.Text = wwqkSYML.sybm;

        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            GlobalMethod.RedirectLogin(Response);
            return;
        }
        //登录人
        this.dlrTextBox.Text = user.name;


        //设置文件名和篇号
        this.InitPH();
        this.SetWJM();
        //中文篇名
        this.zwpmTextBox.Text = "";
        //外文篇名
        this.wwpmTextBox.Text = "";
        //页数
        this.ysTextBox.Text = "";

        //作者
        this.zzTextBox.Text = "";
        //作者单位
        this.zzdwTextBox.Text = "";
        //中文文摘
        this.zwwzTextBox.Text = "";
        //中文主题词
        this.zwztcTextBox.Text = "";
        //外文文摘
        this.wwwzTextBox.Text = "";
        //外文主题词
        this.wwztcTextBox.Text = "";

        //国图分类
        this.gtflTextBox.Text = "";
        //文献标识
        this.wxbsTextBox.Text = "";
        //开本
        this.kbTextBox.Text = "";
    }

    /// <summary>
    /// 从页面中读取片名的信息
    /// </summary>
    /// <returns>返回片名对象</returns>
    private WWQK_PM GetWWQK_PM()
    {
        User user = (User)Session["login"];
        //登陆超时则退到登录页
        if (null == user)
        {
            Response.Write(" <script> top.location = '" + GlobalResource.LOGIN_PAGE + "' </script> ");
            return null;
        }

        WWQK_PM wwqkPM = new WWQK_PM();

        //登录人
        wwqkPM.dlr = user.name;
        //索引编码
        wwqkPM.sybm = this.sybmTextBox.Text.Trim();
        //年份
        wwqkPM.nf = this.nfTextBox.Text.Trim();
        //期号
        wwqkPM.qh = this.qhTextBox.Text.Trim();
        //页数
        try
        {
            wwqkPM.ys = Int32.Parse(this.ysTextBox.Text.Trim());
        }
        catch (Exception)
        {
        }

        //文件名
        wwqkPM.wjm = this.wjmTextBox.Text.Trim();
        //原文件名
        wwqkPM.ywjm = this.ywjmHiddenField.Value.Trim();

        //中文篇名
        wwqkPM.zwpm = this.zwpmTextBox.Text.Trim();
        //外文篇名
        wwqkPM.wwpm = this.wwpmTextBox.Text.Trim();
        //作者
        wwqkPM.zz = this.zzTextBox.Text.Trim();
        //作者单位
        wwqkPM.zzdw = this.zzdwTextBox.Text.Trim();
        //开本
        wwqkPM.kb = this.kbTextBox.Text.Trim();
        //中文文摘
        wwqkPM.zwwz = this.zwwzTextBox.Text.Trim();
        //外文文摘
        wwqkPM.wwwz = this.wwwzTextBox.Text.Trim();
        //中文主题词
        wwqkPM.zwztc = this.zwztcTextBox.Text.Trim();
        //外文主题词
        wwqkPM.wwztc = this.wwztcTextBox.Text.Trim();

        //国图分类
        wwqkPM.gtfl = this.gtflTextBox.Text.Trim();
        //文献标识
        wwqkPM.wxbs = this.wxbsTextBox.Text.Trim();
        //更新日期
        wwqkPM.gxrq = DateTime.Today;

        return wwqkPM;
    }
    protected void submitButton_Click(object sender, EventArgs e)
    {
        //验证外文篇名
        if (!this.ValidateWWPM())
        {
            return;
        }

        //验证文件名
        if (!this.ValidateWJM())
        {
            return;
        }
        //验证上传文件
        if (!this.ValidateYWJMFileUpload())
        {
            return;
        }

        //判断要上传的文件是否已经上传过
        if (IsDuplicate(this.ywjmFileUpload.FileName))
        {
            return;
        }
        //获取外文期刊篇名信息
        WWQK_PM wwqkPM = this.GetWWQK_PM();

        //上传文件
        if (OperationFile.Upload(this.ywjmFileUpload, wwqkPM.wjm))
        {
            //存储外文期刊篇名信息
            this.wwqkDAO.insertWwqkPM(wwqkPM);

            //更新年份区间
            this.UpdateSYMLSLNF(wwqkPM);
            Response.Write("<Script>alert('添加外文期刊篇名信息成功')</Script>");
            //设置下一篇名
            this.BindData();
        }
        else
        {
            String message = "错误：添加外文期刊篇名信息失败";
            Response.Redirect(GlobalResource.ERROR_PAGE+"?message="+message);
            return;
        }
        
    }
    /// <summary>
    /// 验证外文篇名
    /// </summary>
    /// <returns>验证是否通过</returns>
    private Boolean ValidateWWPM()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.wwpmTextBox.Text || "".Equals(this.wwpmTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：外文篇名不能为空";
            flag = false;
        }
        else
        {
            //查找是否存在重复的外文期刊篇名
            if (!this.wwqkDAO.ValidateWWQK_PM(this.wjmTextBox.Text, this.zwpmTextBox.Text.Trim()))
            {
                this.errorLabel.Text = "错误：该外文篇名已存在";
                flag = false;
            }
        }
        return flag;
    }

    /// <summary>
    /// 验证文件名
    /// </summary>
    /// <returns>验证是否通过</returns>
    private Boolean ValidateWJM()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.wjmTextBox.Text || "".Equals(this.wjmTextBox.Text.Trim()))
        {
            this.errorLabel.Text = "错误：文件名不正确";
            flag = false;
        }
        else
        {
            WWQK_PM wwqkPM = this.wwqkDAO.getWwqkPMByWjm(this.wjmTextBox.Text.Trim());
            if (null != wwqkPM)
            {
                this.errorLabel.Text = "错误：文件名已存在";
                flag = false;
            }
        }
        return flag;
    }

    /// <summary>
    /// 验证上传文件
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateYWJMFileUpload()
    {
        this.errorLabel.Text = "";
        Boolean flag = true;
        if (null == this.ywjmFileUpload || !this.ywjmFileUpload.HasFile)
        {
            this.errorLabel.Text = "错误：请选择上传的文件";
            flag = false;
        }
        else
        {
            if (!this.ywjmFileUpload.FileName.EndsWith(".PDF", true, null))
            {
                this.errorLabel.Text = "错误：请选择PDF类型文件";
                flag = false;
            }
            else
            {
                PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
                if (null != pdf)
                {
                    //文件大小不能超过10M
                    if (pdf.FileLength >= 10 * 1024 * 1024)
                    {
                        this.errorLabel.Text = "错误：选择的文件大小超过了10M";
                        pdf.Close();
                        return false;
                    }

                    this.ysTextBox.Text = pdf.NumberOfPages.ToString();
                    this.ywjmHiddenField.Value = this.ywjmFileUpload.FileName;
                }
               
                pdf.Close();
            }
        }
        return flag;
    }

    protected void resetButton_Click(object sender, EventArgs e)
    {
        this.BindData();
    }

    /// <summary>
    /// 验证年份
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateNF()
    {
        Boolean flag = true;
        int year = 0;

        if (null==this.nfTextBox.Text||this.nfTextBox.Text.Trim().Length != 4)
        {
            flag = false;
        }
        else
        {
            this.nfTextBox.Text = this.nfTextBox.Text.Trim();
            try
            {
                year = Int32.Parse(this.nfTextBox.Text);
            }
            catch (Exception)
            {
                flag = false;
            }
            if (year < 1000)
            {
                flag = false;
            }
        }
        return flag;
    }

    /// <summary>
    /// 验证期号
    /// </summary>
    /// <returns></returns>
    private Boolean ValidateQH()
    {
        Boolean flag = true;
        int qh = 0;

        if (null == this.qhTextBox.Text || this.qhTextBox.Text.Trim().Length != 2)
        {
            flag = false;
        }
        else
        {
            this.qhTextBox.Text = this.qhTextBox.Text.Trim();
            try
            {
                qh = Int32.Parse(this.qhTextBox.Text);
            }
            catch (Exception)
            {
                flag = false;
            }
        }
        return flag;
    }


    /// <summary>
    /// 初始化篇号列表
    /// </summary>
    private void InitPH()
    {
        //清空phDropDownList的选择项
        this.phDropDownList.Items.Clear();
        //目录文件名
        String catalogWjm = this.sybmTextBox.Text + "-" + this.nfTextBox.Text + "-" + this.qhTextBox.Text + "-000.PDF";
        //获取流水号为000的篇名
        WWQK_PM wwqkPM = this.wwqkDAO.getWwqkPMByWjm(catalogWjm);
        if (null == wwqkPM)
        {
            this.phDropDownList.Items.Add("000");
            //this.phDropDownList.Items[0].Selected = true;
        }

        //获取中文期最大文件名得篇名
        wwqkPM = this.wwqkDAO.getMaxWwqkPM(this.sybmTextBox.Text, this.nfTextBox.Text, this.qhTextBox.Text);
        //没有找到则设为第一个篇名
        if (null == wwqkPM)
        {
            this.phDropDownList.Items.Add( "001");          
        }
        //找到了则为最大篇号+1
        else
        {

            int endIndex = wwqkPM.wjm.LastIndexOf(".");

            String phString = wwqkPM.wjm.Substring(endIndex - 3, 3);

            int ph = 0;

            try
            {
                ph = Int32.Parse(phString);
            }
            catch (Exception)
            {
                return;
            }

            //当前篇号+1
            ph += 1;

            phString = ph.ToString();
            //长度为1
            if (phString.Length == 1)
            {
                phString = "00" + phString;
            }
            else if (phString.Length == 2)
            {
                phString = "0" + phString;
            }
            else if (phString.Length > 3)
            {
                String message = "错误：篇名数量已经超过了1000篇";
                Response.Redirect(GlobalResource.ERROR_PAGE + "?message=" + message);
                return;
            }

            this.phDropDownList.Items.Add(phString);
            //this.phDropDownList.Items[this.phDropDownList.Items.Count-1].Selected = true;
        }
        //如果只有一个选项则，选择该选项
        this.phDropDownList.Items[0].Selected = true;

    }

    /// <summary>
    /// 设置文件名
    /// </summary>
    private void SetWJM()
    {
        this.wjmTextBox.Text = this.sybmTextBox.Text+"-"+this.nfTextBox.Text+"-"+this.qhTextBox.Text+"-"+this.phDropDownList.SelectedItem.Value+".PDF";
    }

   
    /// <summary>
    /// 作者内容发生变化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void zzTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzTextBox.Text = GlobalMethod.Semicolon(this.zzTextBox.Text);
    }
    protected void zzdwTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zzdwTextBox.Text = GlobalMethod.Semicolon(this.zzdwTextBox.Text);
    }
    protected void zwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.zwztcTextBox.Text = GlobalMethod.Semicolon(this.zwztcTextBox.Text);
    }
    protected void wwztcTextBox_TextChanged(object sender, EventArgs e)
    {
        this.wwztcTextBox.Text = GlobalMethod.Semicolon(this.wwztcTextBox.Text);
    }

    /// <summary>
    /// 更索引目录年份区间信息
    /// </summary>
    /// <param name="wwqkPM">篇名信息</param>
    private void UpdateSYMLSLNF(WWQK_PM wwqkPM)
    {
        if (null == wwqkPM)
        {
            return;
        }

        WWQK_SYML wwqkSYML = this.wwqkDAO.getWwqkSYMLBySybm(wwqkPM.sybm);
        if (null == wwqkSYML)
        {
            return;
        }

        //获取新增篇名的年份
        int nf = 0;
        try
        {
            nf = Int32.Parse(wwqkPM.nf);
        }
        catch (Exception)
        {
        }
        //判断索引目录收录年份是否为空
        if (null == wwqkSYML.slnf || "".Equals(wwqkSYML.slnf))
        {
            //设置新的收录区间
            wwqkSYML.slnf = wwqkPM.nf + "～" + wwqkPM.nf;
            //最新年份
            try
            {
                wwqkSYML.zxnf = nf;
            }
            catch (Exception)
            {
            }
            //年份区间
            wwqkSYML.nfqj = 1;
        }


        //索引目录收录年份不为空，更新收录年份
        String[] slnf = wwqkSYML.slnf.Split('～');

        if (slnf.Length < 2)
        {
            return;
        }
        //起始年份
        int qsnf = 0;
        try
        {
            qsnf = Int32.Parse(slnf[0]);
        }
        catch (Exception)
        {
        }
        //最新年份
        int zxnf = 0;
        try
        {
            zxnf = Int32.Parse(slnf[1]);
        }
        catch (Exception)
        {
        }

        //判断年份区间是否有更新
        Boolean flag = false;
        //起始年份是否大于新增篇名年份
        if (qsnf > nf)
        {
            qsnf = nf;
            flag = true;
        }
        //最新年份是否小于新增篇名年份
        if (zxnf < nf)
        {
            zxnf = nf;
            flag = true;
        }

        //年份区间有变化，则更新索引目录的年份区间
        if (flag)
        {
            //收录年份
            wwqkSYML.slnf = qsnf + "～" + zxnf;
            //计算新的年份区间
            wwqkSYML.nfqj = zxnf - qsnf + 1;
            //最新年份
            wwqkSYML.zxnf = zxnf;

            //更新索引目录信息
            this.wwqkDAO.updateWwqkSYMLBySYBM(wwqkSYML);
        }
    }

    protected void phDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        this.SetWJM();
    }


    /// <summary>
    /// 判断输入文件是否已经上传过，判重标准：原文件名、文件大小、页数都相同
    /// </summary>
    /// <param name="ywjm"></param>
    /// <returns>true表示有重复；false是无重复</returns>
    private Boolean IsDuplicate(String ywjm)
    {
        this.errorLabel.Text = "";
        Boolean flag = false;
        IList<WWQK_PM> list = this.wwqkDAO.getWwqkPMByYwjm(ywjm);
        //读取上传文件的信息：文件大小及页数
        PdfReader pdf = new PdfReader(this.ywjmFileUpload.FileBytes);
        int size = pdf.FileLength;
        int pageCount = pdf.NumberOfPages;
        pdf.Close();

        //判重，判重准则：相同原文件名的PDF文件文件大小和页数都相同则为重复文件
        String filePath = null;
        foreach (WWQK_PM wwqkPM in list)
        {
            filePath = OperationFile.FormatPath(wwqkPM.wjm)+wwqkPM.wjm;
            try
            {
                pdf = new PdfReader(filePath);
                if (null != pdf)
                {
                    if (size == pdf.FileLength && pageCount == pdf.NumberOfPages)
                    {
                        flag = true;
                    }
                }
                pdf.Close();
            }
            catch (Exception)
            {
            }
            //flag为true，则说明已经找到重复
            if (flag)
            {
                this.errorLabel.Text = "错误：你选择上传的文件已经上传过了";
                break;
            }
        }

        return flag;
    }
}